package com.lagou.service;

import com.lagou.handler.UserServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.stereotype.Service;

/**
 * Created by seemygo on 2021/1/14.
 */
@Service
public class UserServiceImpl implements IUserService{
    /**
     * 为将来客户端提供远程调用的方法
     * @param msg
     * @return
     */
    public String sayHello(String msg) {
        System.out.println("are you ok ? "+msg);
        return "服务器返回数据 : "+msg;
    }


    //创建一个方法启动服务器
    public static void startServer(String ip,String port) throws InterruptedException {
        //1,创建两个线程池对象 bossGroup workGroup
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        //2,创建服务端的启动引导对象
        ServerBootstrap serverBootstrap=new ServerBootstrap();

        //3,配置启动引导对象
        serverBootstrap.group(bossGroup,workGroup)
                //channel方法指定服务器监听的通道类型
                .channel(NioServerSocketChannel.class)
                //设置管道处理器 每一个客户端连接进来后 给定一个监听器进行处理
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        //传输通道
                        ChannelPipeline pipeline=ch.pipeline();
                        //在通道上添加通道的处理器  改处理器可能还是一个监听器
                        pipeline.addLast(new StringEncoder());
                        //pipeline.addLast(new StringDecoder());
                        //服务端进行json解码
                        pipeline.addLast( new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        //监听器上监听我们自己的处理方式
                        /*pipeline.addLast(new SimpleChannelInboundHandler<String>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
                                System.out.println(msg);
                            }
                        });*/
                        pipeline.addLast(new UserServerHandler());
                    }
                });

        //bind绑定监听端口
        ChannelFuture cf = serverBootstrap.bind(8999).sync();
        System.out.println(" tcp server start success..");

        //会阻塞等待直到服务器的channel关闭成功
        //cf.channel().closeFuture().sync();
    }
}
